package com.sf.su.marathon.quart;
import com.sf.su.marathon.dao.domain.Group;
import com.sf.su.marathon.dao.domain.ProMarket;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;
import java.util.concurrent.TimeUnit;
import com.sf.su.marathon.manager.GroupManager;
import com.sf.su.marathon.manager.ProMarketManager;
import com.sf.su.marathon.utils.DateUtils;
import com.sf.su.marathon.utils.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;



/**
 * @author 591030 on 2017/12/15.
 */
@Component
public class QuartJob  implements InitializingBean,DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(QuartJob.class);

    private ExecutorService executor;

    private static ScheduledExecutorService jobExecutorService;

    @Autowired
    private ProMarketManager proMarketManager;

    @Autowired
    private GroupManager groupManager;

    @Override
    public void destroy() throws Exception {
        if(jobExecutorService !=null) {
            jobExecutorService.shutdown();
        }

        if(executor!=null) {
            executor.shutdown();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        jobExecutorService= Executors.newSingleThreadScheduledExecutor();
        jobExecutorService.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run() {
                try {
                    System.out.println("111111111");
                    runProMarket();
                    runGroup();
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getLocalizedMessage());
                }
            }
        }, 10, 5, TimeUnit.SECONDS);
    }

    private void runProMarket(){
        List<ProMarket> marketList = proMarketManager.selectAll();
        for (ProMarket proMarket :marketList) {
            List<Group> groupList = groupManager.getByMarketId(proMarket.getMktId());
            if(groupList!=null && !groupList.isEmpty()){
                continue;
            }
            if (StringUtils.isEmpty( proMarket.getGroupDuration())){
                continue;
            }
            if (StringUtils.isEmpty(proMarket.getLastGroupTime())){
                continue;
            }
            Long expireDate = proMarket.getGroupDuration() *60 *1000 + proMarket.getLastGroupTime().getTime();
            //拼团周期到期
            if(System.currentTimeMillis() > expireDate){
                createNewGroup(proMarket);
            }
        }
    }

    private void runGroup() {
        List<Group> groupList = groupManager.selectNotFullAndExpire();
        for(Group group : groupList) {
            if(System.currentTimeMillis() > group.getExpireDate().getTime()) {
                Group newOne = new Group();
                ProMarket proMarket = proMarketManager.getProMarketInfo(group.getProMarketId());
                Integer currentPeriod = proMarket.getCurrentPeriod()+ 1;
                newOne.setId(UUIDUtils.getUUID());
                newOne.setType(group.getType());
                newOne.setState(0);
                newOne.setPeriodIndex(String.valueOf(currentPeriod));
                newOne.setIsFull(false);
                newOne.setTotalCount(group.getTotalCount());
                newOne.setExpireDate(DateUtils.getTimeBeforeMinutes(0-proMarket.getGroupDuration()));
                newOne.setGroupName(proMarket.getMktNameShow() + currentPeriod);
                newOne.setProMarketId(group.getProMarketId());

                proMarket.setCurrentPeriod(proMarket.getCurrentPeriod() +1);
                proMarket.setLastGroupTime(newOne.getExpireDate());
                groupManager.insert(newOne);
                proMarketManager.updateByPrimaryKeySelective(proMarket);
            }
        }

    }

    private void createNewGroup(ProMarket proMarket){
        Group group = new Group();
        int currentPeriod = 1;
        group.setId(UUIDUtils.getUUID());
        group.setGroupName(proMarket.getMktNameShow() + proMarket.getCurrentPeriod());
        group.setCurrentCount(0);
        group.setTotalCount(proMarket.getGroupLimit());
        group.setExpireDate(DateUtils.getTimeBeforeMinutes(0 - proMarket.getGroupDuration()));
        group.setIsFull(false);
        group.setPeriodIndex(String.valueOf(currentPeriod));
        group.setState(0);
        group.setType(0);
        group.setProMarketId(proMarket.getMktId());
        int count = groupManager.insert(group);
        if(count > 0 ){
            proMarket.setCurrentPeriod(currentPeriod);
            proMarketManager.updateByPrimaryKeySelective(proMarket);
        }
    }


}
